<template>
	<view style="display: block;">
		<!-- 404页面 -->
		<view class="noData" v-if="netWorkType == 'none'">
			<noData @handle="refresh"></noData>
		</view>
		<view v-if="netWorkType != 'none'">
			<view class="tabr" :style="{top:headerTop}">
				<view :class="current==index ? 'current' : ''" v-for="(item,index) in tabList" :key='index' @tap="switchType(item,index)">
					{{item.name}}
				</view>
			</view>
			<view class="place"></view>

			<!-- new -->
			<view style="margin-top:114rpx;">
				<view class="margin-all15"  :class="[current==2 ? 'gray-box' : '']">
					<view class="margin-bottom15 bg-white border-radius8 padtop10 padbottom10" v-for="(item,index) in data.allList">
						<view  :class="[current==2 ? 'flex-start-box' : 'flex-box']">
							<view class="item padleft20">
								<view :class="[current==2 ? '' : 'red-txt']">
									<text class="font12">￥</text><text class="font21 font-bold">{{item.coupon_money}}</text>
								</view>
								<view class="padtop5 font12 font-gray2">优惠券</view>
							</view>
							<view class="item" :class="[current==2 ? 'marginleft20' : '']">
								<view class="font16 font-bold padbottom5 over-ellipsis set-width" style="width: 300rpx;">
									{{item.name}}
								</view>
								<view class="font12 font-gray2 padbottom5">
									{{item.use_expire_at}} 到期
								</view>
								<view class="font12 font-gray2">
									满{{item.spend_money}}元可用 
								</view>
							</view>
							<!-- 可使用和过期 -->
							<!-- 二维码 -->
							<view @tap='showQrcode(item,index)' v-if="(current==0 || current==2) && item.is_store_write_off==1 && item.status!=4" class="iconfont font28 blue-icon padright20">
								&#xe6e5;
							</view>
							
							<!-- 已使用 -->
							<view class="font12 padright15 font-gray2" v-if="(current==0 || current==2) && item.is_store_write_off==1 && item.status==4">已使用</view>

							<!-- 领券中心 -->
							<view   v-if="current==1 && item.is_receive==1"  class="get-btn marginright20 complete font14">
								已领取
							</view>
							<view @tap="receive(item.id)"  v-if="current==1 && item.is_receive==0"  class="get-btn marginright20 font14">
								领取
							</view>

						</view>
						<view>
							<image class="publicImg" :src="OSS_HOST+'img/coupon-dash-line.png'"  mode="widthFix"></image>
						</view>
						<view class="flex-box padleft20">
							<!-- <view class="item font12 font-gray2" v-if="item.limit_type == 4">
								可用门店：指定门店可用
							</view> -->
							<view class="item font12 font-gray2" >
								使用范围：<!-- {{item.limit_type_name}} -->
								<text v-if="item.limit_type == 0">无限制</text>
								<text v-if="item.limit_type == 1">类别可用</text>
								<text v-if="item.limit_type == 2">单品可用</text>
								<text v-if="item.limit_type == 3">自定义产品可用</text>
								<text v-if="item.limit_type == 4">门店可用</text>
								<text v-if="item.limit_type == 5">门店核销可用</text>
							</view>
							<view @tap="viewUseRule(item,index)" class=" font12 font-gray2 padright20">
								使用规则<text class="iconfont padleft5">&#xe689;</text>
							</view>
						</view>

						<!-- 收缩部分 -->
						<view class="fold padtop10 padleft20" v-if="index===curentActive">
							<view class="font12 font-gray2">
								
								{{item.use_rules}}
							</view>
							<!-- <view class="font12 font-gray2">
								请在结账时向收银员出示
							</view>
							<view class="font12 font-gray2">
								最终解释权归小欧科技所有
							</view> -->
						</view>
					</view>


				</view>

			</view>

			<!-- new end -->
			<!-- <view class="list" style="margin-top: 70rpx;">
					<coupon current='0' key='received' ref='received' :couponList='data.list' v-if="current==0">
					</coupon>
					<coupon current='3'  key='expired'  ref='expired' :couponList='data.expireList' v-if="current==1">
					</coupon>
				</view> -->
			<!-- 提示弹框 -->
			<tui-tips ref="toast"></tui-tips>
			<!-- 二维码弹窗 -->
			<uni-popup id="qrcodePopup" ref="qrcodePopup" type='center'  style="position: relative;">
				<view>
					<view class="view-qrcode-box" style="width:600rpx;position: relative;">
						<image :src="OSS_HOST+'img/view-qrcode-bg.png'"  mode="widthFix" class="publicImg"></image>
						<view class="content">
							<view style="display: flex;align-items: center;height: 100%;">
								<view class="bg-white border-radius15 margin-all20 padtop15 padbottom10" style="width: 100%;text-align: center;">
									<view class="font16 padbottom5 font-bold">优惠券核销二维码</view>
									<view class="font16 red-txt">满{{currentCoupon.spend_money}}减{{currentCoupon.coupon_money}}元</view>
									<view style="margin-top: 30rpx;">
										<image mode="widthFix" class="publicImg" :src="OSS_HOST+'img/view-qrcode-line.png'" ></image>
									</view>
									
									<view class="margintop20 font-gray2 padtop15">
										请向门店收银员出示二维码
									</view>
									<view style="height:184px;width:184px;margin: auto;margin-top:24rpx;">
										<canvas :class="[isShow ? '' :'canvas-hide']" canvas-id="qrcode" style=" height:184px;width:184px;" />
									</view>
									<!-- <view style="width:300rpx;margin: auto;margin-top:60rpx;">
										<image mode="widthFix" class="publicImg" src="../../../../static/img.png"></image>
									</view> -->
								</view>
							</view>
							
						</view>
						
					</view>
					<view style="margin-top: 36rpx;text-align: center;z-index: 999;" @tap="closeQrcodePopup">
						<icon type="clear" size="26" />
					</view>
				</view>
				
				
				
				
			</uni-popup>
			<!-- 登录弹框 -->
			<uni-popup-vlogin id="popupvLogin" ref="popupvLogin" type="bottom" />
		</view>
	</view>
</template>
<script>
	import {oss_host} from '@/config/config.js';	
	import uQRCode from '@/common/uqrcode.js'
	import {
		mapGetters
	} from 'vuex';
	import coupon from "@/components/coupon/coupon"
	export default {
		components: {

			coupon 
		},

		data() {
			return {
				// 图片链接站点
				OSS_HOST: oss_host,
				currentCoupon:{
					coupon_money:0,
					spend_money:0
				},
				timemer:null,
				isShow:false,
				curentActive: null,
				current: 0,
				tabList: [{
					name: '可使用'
				}, {
					name: '领券中心'
				}, {
					name: '已过期'
				}],
				//网络状态
				networkStatus: true,
				//接口数据
				data: {
					allList:[],
					list2: [{
						name: '新会员',
						id: 1
					}, {
						name: '新会员',
						id: 2
					}],
					list: [
						// 	{id:1,title:"日常用品立减10元",termStart:"2019-04-01",termEnd:"2019-05-30",ticket:"10",criteria:"满50使用"},
						// {id:2,title:"家用电器立减100元",termStart:"2019-04-01",termEnd:"2019-05-30",ticket:"100",criteria:"满500使用"},
						// {id:3,title:"全场立减10元",termStart:"2019-04-01",termEnd:"2019-05-30",ticket:"10",criteria:"无门槛"},
						// {id:4,title:"全场立减50元",termStart:"2019-04-01",termEnd:"2019-05-30",ticket:"50",criteria:"满1000使用"}
					],
					receiveList: [],
					//过期的优惠券
					expireList: []
				},
				headerTop: 1,
				//控制滑动效果
				typeClass: 'valid',
				subState: '',
				theIndex: null,
				oldIndex: null,
				isStop: false,
				//购买状态，从订单页过来，把状态改成true
				buyStatus: 1,
				//订单的金额
				payment: 50
			}
		},
		computed: {
			...mapGetters(['netWorkType'])
		},
		onPageScroll(e) {

		},
		//下拉刷新，需要自己在page.json文件中配置开启页面下拉刷新 "enablePullDownRefresh": true
		onPullDownRefresh() {
			setTimeout(function() {
				uni.stopPullDownRefresh();
			}, 1000);
		},
		onLoad(e) {
			if (typeof e.buyStatus != "undefined") {
				this.buyStatus = Boolean(e.buyStatus)
			}

			if (typeof e.payment != "undefined") {
				this.payment = e.payment
				console.log(this.payment)
			}
			//兼容H5下排序栏位置
			// #ifdef H5
			//定时器方式循环获取高度为止，这么写的原因是onLoad中head未必已经渲染出来。
			let Timer = setInterval(() => {
				let uniHead = document.getElementsByTagName('uni-page-head');
				if (uniHead.length > 0) {
					this.headerTop = uniHead[0].offsetHeight + 'px';
					clearInterval(Timer); //清除定时器
				}
			}, 1);
			// #endif

		},
		onShow() {
			//this.$refs.qrcodePopup.open()
			this.getList()
		},
		methods: {
			
			closeQrcodePopup(){
				this.isShow=false;
				this.$refs.qrcodePopup.close();
			},
			
			showQrcode(row,i){
				let _this = this;
				this.currentCoupon.coupon_money=row.coupon_money;
				this.currentCoupon.spend_money=row.spend_money;
				//过期则不弹二维码窗
				if(this.current==2){
					return ;
				}				
									
				  // 回调方式
				  
					this.$refs.qrcodePopup.open();
					
					let obj={
						name:row.name,
						coupon_id:row.id,
						code_type:2,
						desc:row.used_tip_text,
						price:row.coupon_money,
						coupon_price:row.spend_money,
						type:1
						
					}
					 clearTimeout(this.timemer)
					 this.timemer=setTimeout(function(){
						 _this.isShow=true;
						 uQRCode.make({
						   canvasId: 'qrcode',
						   componentInstance: this,
						   text: JSON.stringify(obj),
						   size:184,
						   margin: 10,
						   backgroundColor: '#ffffff',
						   foregroundColor: '#000000',
						   fileType: 'jpg',
						   correctLevel: uQRCode.errorCorrectLevel.H,
						  
						 }).then(res=>{
						 						 console.log(res)
						 							  
						 })
					 },500)
					 
					 
					 
			 
			},
			viewUseRule(row, index) {

				if (this.curentActive == index) {
					this.curentActive = null;
				} else {
					this.curentActive = index;
				}
				console.log(this.curentActive)
			},
			// 刷新的方法
			refresh() {
				this.getList();
			},
			getList() {
				const _this = this

				//提交ajax
				var opt = {
					url: '/coupon/my',
					data: {},
					success: function(res) {
						//console.log(res)
						if (res.status == 1) {
							_this.data.list = res.data.list
							_this.data.expireList = res.data.expireList;
							_this.data.receiveList = res.data.receive;
							_this.data.receiveList.forEach(res=>{
								res.use_expire_at=res.receive_expire_at
							})
							
							//删掉不满足条件的券
							_this.data.list.forEach(function(cv) {
								cv.startTime = cv.use_start_at;
								cv.tag = cv.tag || '优惠券';
								cv.endTime = cv.use_expire_at;
								cv.tips = cv.used_tip_text
							});
							_this.data.expireList.forEach(function(cv) {
								cv.startTime = cv.use_start_at;
								cv.tag = cv.tag || '优惠券';
								cv.endTime = cv.use_expire_at;
								cv.tips = cv.used_tip_text
							});
							console.log('curr---',_this.current)
							let i = _this.current;
							if(i==1){
								_this.data.allList=[]
								_this.data.allList=_this.data.receiveList
							}else if(i==2){
								_this.data.allList=[]
								_this.data.allList=_this.data.expireList;
							}else if(i==0){
								_this.data.allList=[]
								_this.data.allList=_this.data.list;
							}
							// _this.data.allList=_this.data.list;

						} else {
							uni.showToast({
								icon: 'none',
								title: res.message
							});
						}

					}
				};

				_this.$service.GetApi(opt)

			},
			switchType(item, i) {
				this.current = i;
				   
				this.getList(); 
				 
			},
			//领取优惠券
			receive(id) {
				const _this = this
				//提交ajax
				var opt = {
					url: '/coupon/receive',
					data: {
						coupon_id: id
					},
					success: function(res) {
						//console.log(res)
						if (res.status == 1) {
							let options = {
								msg: res.message,
								type: 'green'
							};
							_this.$refs.toast.showTips(options);
						} else {
							let options = {
								msg: res.message,
								type: 'danger'
							};
							_this.$refs.toast.showTips(options);
						}

					}
				};
				_this.$service.GetApi(opt)
			},
			//控制左滑删除效果-begin
			touchStart(index, event) {
				this.isStop = true;
				//可领取页，不可以左滑
				if (this.typeClass == 'valid') {
					this.isStop = true;
				}

				//多点触控不触发
				if (event.touches.length > 1) {
					this.isStop = true;
					return;
				}
				this.oldIndex = this.theIndex;
				this.theIndex = null;
				//初始坐标
				this.initXY = [event.touches[0].pageX, event.touches[0].pageY];
			},
			touchMove(index, event) {
				//多点触控不触发
				if (event.touches.length > 1) {
					this.isStop = true;
					return;
				}
				let moveX = event.touches[0].pageX - this.initXY[0];
				let moveY = event.touches[0].pageY - this.initXY[1];

				if (this.isStop || Math.abs(moveX) < 5) {
					return;
				}
				if (Math.abs(moveY) > Math.abs(moveX)) {
					// 竖向滑动-不触发左滑效果
					this.isStop = true;
					return;
				}

				if (moveX < 0) {
					this.theIndex = index;
					this.isStop = true;
				} else if (moveX > 0) {
					if (this.theIndex != null && this.oldIndex == this.theIndex) {
						this.oldIndex = index;
						this.theIndex = null;
						this.isStop = true;
						setTimeout(() => {
							this.oldIndex = null;
						}, 150)
					}
				}
			},

			touchEnd(index, $event) {
				//解除禁止触发状态
				this.isStop = false;
			},

			//删除商品   未实现
			deleteCoupon(id, List) {
				const _this = this

				//提交ajax
				var opt = {
					url: '/index/index',
					data: {},
					success: function(res) {
						//console.log(res)
						if (res.status == 1) {
							this.deleteLocalCoupon(id, List)
							let options = {
								msg: res.message,
								type: 'green'
							};
							_this.$refs.toast.showTips(options);
						} else {
							let options = {
								msg: res.message,
								type: 'danger'
							};
							_this.$refs.toast.showTips(options);

						}

					}
				};

				_this.$service.GetApi(opt)
			},
			//删除本地优惠券
			deleteLocalCoupon() {
				let len = List.length;
				for (let i = 0; i < len; i++) {
					if (id == List[i].id) {
						List.splice(i, 1);
						break;
					}
				}
				this.oldIndex = null;
				this.theIndex = null;
			},
			//使用优惠券
			used(id, coupon_id, name, coupon_money) {
				const _this = this
				//订单页跳转过来
				if (this.buyStatus) {
					//选择优惠券						
					let data = {
						coupon_id: coupon_id,
						name: name,
						coupon_money: coupon_money
					}
					uni.setStorage({
						key: 'selectCoupon',
						data: data,
						success: () => {
							uni.navigateBack()
						}
					})
					return
				}
				//================================================订单跳转过来使用优惠券   结束
				// uni.navigateTo({
				// 	url: '/pages/index/lease/lease'
				// })
				_this.$refer.setVilit('/pages/index/lease/lease')
				let callback = function(url) {
					_this.$refs.popupvLogin.open()
				}
				_this.$refer.toUrl(callback)


			},
			discard() {
				//丢弃
			}


		}
	}
</script>
<style lang="scss">
	@import "./coupon.scss";
</style>
